package com.bianmaba.oauth2.authserver.application.configuration;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by cwx183898 on 2017/8/9.
 */
@Configuration
@EnableOAuth2Sso
@ConfigurationProperties("security.oauth2.client")
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private static final Log LOGGER = LogFactory.getLog(SecurityConfiguration.class);


    private String logoutUrl = null;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated();
        http.formLogin().loginPage("/login").permitAll();

        http.logout().permitAll().logoutSuccessHandler(new LogoutSuccessHandler() {
            //注销流程：用户调用本应用的/logout成功时，将执行此handler，此handler将重定向页面到Authorization-server的/logout，注销成功后重定向到redirect_uri
            @Override
            public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                String redirect = request.getParameter("redirect_uri");
                if (redirect == null || redirect.trim().isEmpty()) {
                    redirect = "/";
                }
                if (!StringUtils.isEmpty(logoutUrl)) {
                    response.sendRedirect(logoutUrl + "?redirect_uri=" + redirect);
                } else {
                    response.sendRedirect(redirect);
                }
            }
        });
        http.csrf().disable();
    }

    public String getLogoutUrl() {
        return logoutUrl;
    }

    public void setLogoutUrl(String logoutUrl) {
        this.logoutUrl = logoutUrl;
    }
}
